/**
 * Copyright � 2012 GestureSoft. ALL RIGHTS RESERVED.
 * This file contains proprietary and GestureSoft CONFIDENTIAL Information.
 * Use, disclosure or reproduction is prohibited.
 * 
 * @fileName Socialize.as
 * @creationDate Aug 8, 2012
 * @author 
 * @version 1.0
 */
package com.gesturesoft.imultimax.socialize
{
	import com.gesturesoft.imultimax.AppConst;
	import com.gesturesoft.imultimax.model.AppModel;
	import com.gesturesoft.imultimax.socialize.events.AuthenticationEvent;
	import com.gesturesoft.imultimax.socialize.facebook.FacebookService;
	import com.gesturesoft.imultimax.socialize.facebook.FacebookStageWebView;
	import com.gesturesoft.imultimax.socialize.facebook.LogoutStageWebView;
	import com.gesturesoft.imultimax.socialize.google.GoogleService;
	import com.gesturesoft.imultimax.socialize.google.GoogleStageWebView;
	import com.gesturesoft.imultimax.socialize.twitter.TwitterService;
	import com.gesturesoft.imultimax.socialize.twitter.TwitterStageWebView;
	import com.gesturesoft.imultimax.views.components.BusyCancelUI;
	import com.gesturesoft.imultimax.views.components.BusyPopUp;
	import com.gesturesoft.imultimax.views.components.CancelUI;
	import com.gesturesoft.imultimax.views.components.PrimaryAuthenticationView;
	
	import flash.display.DisplayObject;
	import flash.display.Stage;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.LocationChangeEvent;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.media.StageWebView;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	
	import mx.core.FlexGlobals;
	import mx.managers.PopUpManager;
	import mx.managers.SystemManager;
	
	import spark.components.View;

	public class Socialize extends EventDispatcher
	{
		public static const FACEBOOK:String = "facebook";
		public static const TWITTER:String = "twitter";
		public static const GOOGLE:String = "google";
		public static const YAHOO:String = "yahoo";
		public static const AOL:String = "aol";
		public static const HOTMAIL:String = "hotmail";
		public static const LINKEDIN:String = "linkedin";
		
		private var protocolType:String = "https";
		
		[Bindable]private var busyPopUp:BusyCancelUI;
		[Bindable]private var cancelUI:CancelUI;
		
		//Facebook Service
		private var facebookService:FacebookService;
		private var facebookUI:FacebookStageWebView;
		private var logoutWebView:LogoutStageWebView;
		
		//Titter Service
		private var twitterService:TwitterService;
		private var twitterUI:TwitterStageWebView;
		
		//Google Service
		private var googleService:GoogleService;
		private var googleUI:GoogleStageWebView;
		
		private var currentView:View;
		private var currentApi:String;
		
		public function Socialize()
		{
			
			//Constructor
			if(AppModel.getInstance().targetPlatform == AppConst.ANDROID)
				protocolType = "http";
			
		}
		
		//Function to get authentication for an api and return true if authenticated / false if not authenticated.
		
		public function getSocialAuth(api:String,view:View):void
		{
			currentView = view;
			currentApi = api;
			var point:Point = new Point(view.x, view.y);
			if(!AppModel.getInstance().offlineMode){
				showBusy(api);
				switch(api)
				{
					
					case FACEBOOK:
					{
						facebookService = new FacebookService();
						facebookUI = new FacebookStageWebView();
						facebookUI.yOffset = (view.contentToGlobal(point)as Point).y;
						facebookUI.heightOffset = 0;
						
						facebookService.appID = "249372981847147";
						facebookService.appName = "iMultiMax";
						facebookService.authURL = protocolType + "://graph.facebook.com/oauth/authorize";
						facebookService.appURL = protocolType + "://warm-bastion-5259.herokuapp.com/";
						facebookService.graphURL = "https://graph.facebook.com/";
						facebookService.accessTokenURL = facebookService.graphURL+"oauth/access_token";
						facebookService.appSecret = "0242567762d8f147908decddc28a1233";
						
						facebookUI.facebookService = facebookService;
						
						// Add listeners to Signals dispatched from facebookService
						facebookService.errorSignal.add(onFacebookError);
						facebookService.userInfoReceived.add(onFacebookUserInfoReceived);
						// Add listeners to Signals dispatched from facebookUI
						facebookUI.locationChangeSignal.add(onFacebookUILocationChange);
						facebookUI.locationChangingSignal.add(onFacebookUILocationChanging);
						facebookUI.completeSignal.add(onFacebookUIComplete);
						
						facebookUI.url = String(facebookService.authURL+
							"?client_id="+facebookService.appID+
							"&redirect_uri="+facebookService.appURL+
							"&display=wap&scope=read_stream,email");
						view.addElement(facebookUI);
						break;
						
					}
					case TWITTER:
					{
						// Encapsulates our business logic
						twitterService = new TwitterService();
						// UIComponent extension
						twitterUI = new TwitterStageWebView();
						twitterUI.yOffset = (view.contentToGlobal(point)as Point).y;
						twitterUI.heightOffset = 0;
						
						// Variables needed by TwitterService
						twitterService.consumerKey = "czmYT3kO1LCi3zmIZA4Ebw";
						twitterService.consumerSecret = "xPIZ01XEg8DyGqk1LvvGyvROpwztRLnQmfwNzTlb4";
						twitterService.authTokenURL = "https://api.twitter.com/oauth/request_token";
						twitterService.accessTokenURL = protocolType + "://api.twitter.com/oauth/access_token";
						twitterService.authorizeURL = protocolType + "://api.twitter.com/oauth/authorize";
						twitterService.applicationName = "iMultiMax";
						
						// Add listeners to Signals dispatched from twitterService
						twitterService.failure.add(onTwitterError);
						twitterService.loginURLReady.add(initStageView);
						twitterService.accessTokenReceived.add(onAccessTokenReceived);
						twitterService.tweetSucces.add(onConnectionFail);
						
						// Add listeners to Signals dispatched from twitterUI
						twitterUI.failureSignal.add(onTwitterError);
						twitterUI.locationChangeSignal.add(onTwitterUILocationChange);
						twitterUI.locationChangingSignal.add(onTwitterUILocationChanging);
						twitterUI.locationCompleteSignal.add(onTwitterUILocationComplete);
						twitterUI.accessTokenReceived.add(onAccessTokenReceived);
						
						// Begin the request process
						twitterService.start();
						
						// Update the UI
						view.addElement(twitterUI);
						break;
						
					}
					case GOOGLE:
					{
						
						googleService = new GoogleService();
						googleUI = new GoogleStageWebView();
						googleUI.yOffset = (view.contentToGlobal(point)as Point).y;
						googleUI.heightOffset = 0;
						
						googleService.clientID = "134697901241.apps.googleusercontent.com";
						googleService.appSecret = "QjkgPLocSGFqjzslyUIJiqpj";
						googleService.userInfoURL = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=";
						googleService.accessTokenURL = "https://accounts.google.com/o/oauth2/token";
						googleService.authURL = "https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile&redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=code&client_id=";
						
						googleUI.googleService = googleService;
						
						// Add listeners to Signals dispatched from googleService
						googleService.errorSignal.add(onGoogleError);
						googleService.userInfoReceived.add(onGoogleUserInfoReceived);
						// Add listeners to Signals dispatched from googleUI
						googleUI.locationChangeSignal.add(onGoogleUILocationChange);
						googleUI.locationChangingSignal.add(onGoogleUILocationChanging);
						googleUI.locationComplete.add(onGoogleUILocationComplete);
						
						googleUI.url = String(googleService.authURL + googleService.clientID + "&approval_prompt=force");
						
						view.addElement(googleUI);
						break;
						
					}
					case YAHOO:
					case AOL:
					case HOTMAIL:
					case LINKEDIN:
					{
						
						break;
						
					}
					default:
					{
						hideBusy();
						this.dispatchEvent(new AuthenticationEvent(AuthenticationEvent.AUTHENTICATION_SUCCESS));
						break;
						
					}
						
				}
			}
			else
			{
				if(currentApi == "")
					this.dispatchEvent(new AuthenticationEvent(AuthenticationEvent.AUTHENTICATION_SUCCESS));
				else
					this.dispatchEvent(new AuthenticationEvent(AuthenticationEvent.AUTHENTICATION_NTWK_FAILED));
			}
			
			
		}
		
		protected function onConnectionFail():void
		{
			
			this.dispatchEvent(new AuthenticationEvent(AuthenticationEvent.AUTHENTICATION_CONN_FAILED));
			
		}
		
		protected function showBusy(title:String):void
		{
			if(busyPopUp)
				hideBusy();
			
			busyPopUp = new BusyCancelUI();
			busyPopUp.addEventListener("cancelClick",onCancelClick);
			busyPopUp.width = currentView.width;
			busyPopUp.height = currentView.height;
			busyPopUp.title = getTitle(title);
			PopUpManager.addPopUp(busyPopUp,currentView);
			PopUpManager.centerPopUp(busyPopUp);
		}
		
		protected function hideBusy():void
		{
			
			if(busyPopUp)
			{
				busyPopUp.removeEventListener("cancelClick",onCancelClick);
				PopUpManager.removePopUp(busyPopUp);
				busyPopUp = null;
			}
			
		}
		
		private function dispatchSuccess(userInfo:Array=null):void
		{
			this.dispatchEvent(new AuthenticationEvent(AuthenticationEvent.AUTHENTICATION_SUCCESS,userInfo));
		}
		
		private function dispatchFail():void
		{
			this.dispatchEvent(new AuthenticationEvent(AuthenticationEvent.AUTHENTICATION_FAILED));
		}
		
		private function onFacebookUILocationChange(event:LocationChangeEvent):void
		{
			
			trace("onFacebookUILocationChange");
			currentView.callLater(faceBookHideLater);
			
		}
		
		private function onFacebookUILocationChanging(event:LocationChangeEvent):void
		{
			
			currentView.callLater(faceBookHideLater);
			
		}
		
		private function onFacebookUIComplete(event:Event):void
		{
			
			trace("onFacebookUILocationChange");
			currentView.callLater(faceBookShowLater);
			
		}
		
		private function onFacebookError(errMessage:String):void
		{
			
			trace("onFacebookError: "+errMessage);
			dispatchFail();
			hideBusy();
			facebookUI.dispose();
			
		}
		
		private function onFacebookUserInfoReceived(userData:Array):void
		{
			
			trace("onFacebookUserInfoReceived");
			dispatchSuccess(userData);
			hideBusy();
			facebookUI.dispose();
			/*if(AppModel.getInstance().targetPlatform == AppConst.ANDROID)
			{*/
				reallyLogout();
			/*}*/
				
		}
		
		private function faceBookHideLater():void
		{
			
			if(!busyPopUp)
			{
				
				showBusy(FACEBOOK);
				
			}
			
			facebookUI.hide();
			
		}
		
		private function faceBookShowLater():void
		{
			
			facebookUI.show();
			hideBusy();
			
		}
		
		private function onGoogleUILocationChange(event:LocationChangeEvent):void
		{
			
			trace("onGoogleUILocationChange");
			currentView.callLater(googleHideLater);			
			
		}
		
		private function onGoogleUILocationChanging(event:LocationChangeEvent):void
		{
			
			trace("onGoogleUILocationChanging");
			currentView.callLater(googleHideLater);	
			
		}
		
		private function onGoogleUILocationComplete(event:Event):void
		{
			
			trace("onGoogleUILocationComplete");
			currentView.callLater(googleShowLater);
			
		}
		
		private function onGoogleError(errMessage:String):void
		{
			
			trace("onGoogleError: "+errMessage);
			dispatchFail();
			hideBusy();
			googleUI.dispose();
			
		}
		
		private function onGoogleUserInfoReceived(userData:Array):void
		{
			
			trace("onGoogleUserInfoReceived");
			dispatchSuccess(userData);
			hideBusy();
			googleUI.dispose();
			
		} 
		
		private function googleHideLater():void
		{
			
			if(!busyPopUp)
			{
				
				showBusy(GOOGLE);
				
			}
			
			googleUI.hide();
			
		}
		
		private function googleShowLater():void
		{
			
			googleUI.show();
			hideBusy();
			
		}
		
		private function initStageView():void
		{
			
			twitterUI.url = twitterService.loginURL;
			
		}
		
		private function onAccessTokenReceived():void
		{
			
			trace("TokenRecieved");
			dispatchSuccess();
			hideBusy();
			twitterUI.dispose();
			
		}
		
		private function onTwitterUILocationChange(event:LocationChangeEvent):void
		{
			
			trace("onTwitterUILocationChangeHandler");
			currentView.callLater(twitterHideLater);			
			
		}
		
		private function onTwitterUILocationChanging(event:LocationChangeEvent):void
		{
			
			trace("onTwitterUILocationChangingHandler");
			currentView.callLater(twitterHideLater);
			
		}
		
		private function onTwitterUILocationComplete(event:Event):void
		{
			
			trace("onTwitterUILocationCompleteHandler");
			currentView.callLater(twitterShowLater);
			
		}
		
		private function onTwitterError(errMessage:*):void
		{
			
			trace("onTwitterError: "+errMessage);
			dispatchFail();
			hideBusy();
			twitterUI.dispose();
			
		}
		
		public function getTwitterAccessToken(code:String):void
		{
			
			twitterService.getAccessToken(code);
			
		}
		
		private function twitterHideLater():void
		{
			
			if(!busyPopUp)
			{
				
				showBusy(TWITTER);
				
			}
			
			twitterUI.hide();
			
		}
		
		private function twitterShowLater():void
		{
			
			twitterUI.show();
			hideBusy();
			
		}
		
		public function getPrimaryAuthProcess(view:View):void
		{
			
			FlexGlobals.topLevelApplication.navigator.pushView(PrimaryAuthenticationView);
			FlexGlobals.topLevelApplication.addEventListener(AuthenticationEvent.AUTHENTICATION_PRIMARY_SUCCESS,onPrimaryAuthSuccess);
			FlexGlobals.topLevelApplication.addEventListener(AuthenticationEvent.AUTHENTICATION_PRIMARY_FAILED,onPrimaryAuthFailed);
			
		}
		
		private function onPrimaryAuthSuccess(e:AuthenticationEvent):void
		{
			
			FlexGlobals.topLevelApplication.removeEventListener(AuthenticationEvent.AUTHENTICATION_PRIMARY_SUCCESS,onPrimaryAuthSuccess);
			FlexGlobals.topLevelApplication.removeEventListener(AuthenticationEvent.AUTHENTICATION_PRIMARY_FAILED,onPrimaryAuthFailed);
			this.dispatchEvent(new AuthenticationEvent(AuthenticationEvent.AUTHENTICATION_PRIMARY_SUCCESS));
			
		}
		
		private function onPrimaryAuthFailed(e:AuthenticationEvent):void
		{
			
			FlexGlobals.topLevelApplication.removeEventListener(AuthenticationEvent.AUTHENTICATION_PRIMARY_SUCCESS,onPrimaryAuthSuccess);
			FlexGlobals.topLevelApplication.removeEventListener(AuthenticationEvent.AUTHENTICATION_PRIMARY_FAILED,onPrimaryAuthFailed);
			this.dispatchEvent(new AuthenticationEvent(AuthenticationEvent.AUTHENTICATION_PRIMARY_FAILED));
			
		}
		
		protected function reallyLogout():void
		{
			
			logoutWebView = new LogoutStageWebView();
			logoutWebView.appUrl = "https://warm-bastion-5259.herokuapp.com/";
			logoutWebView.url = "https://m.facebook.com/logout.php?next=" + logoutWebView.appUrl + "&access_token="+facebookService.accessToken+"&confirm=1";
			logoutWebView.completeSignal.add(onFinish);
			currentView.addElement(logoutWebView);
			
		}
		
		protected function onFinish(e:Event):void
		{
			
			logoutWebView.dispose();
			
		}
		
		public function onCancelClick(e:Event=null):void
		{
			
			switch(currentApi)
			{
				
				case FACEBOOK:
				{
					
					facebookUI.dispose();
					hideBusy();
					dispatchFail();
					break;
					
				}
				
				case GOOGLE:
				{
					
					googleUI.dispose();
					hideBusy();
					dispatchFail();
					break;
					
				}
					
				case TWITTER:
				{
					
					twitterUI.dispose();
					hideBusy();
					dispatchFail();
					break;
					
				}
					
				case YAHOO:
				{
					
					dispatchFail();
					hideBusy();
					break;
					
				}
					
				case AOL:
				{
					
					dispatchFail();
					hideBusy();
					break;
					
				}
					
				case HOTMAIL:
				{
					
					dispatchFail();
					hideBusy();
					break;
					
				}
					
				case LINKEDIN:
				{
					
					dispatchFail();
					hideBusy();
					break;
					
				}
					
				default:
				{
					
					dispatchFail();
					hideBusy();
					break;
					
				}
					
			}
			
		}
		
		protected function getTitle(value:String):String
		{
			
			var mainTitle:String;
			switch(value)
			{
				
				case FACEBOOK:
				{
					
					mainTitle = "Starting Facebook...";
					break;
					
				}
				case TWITTER:
				{
					
					mainTitle = "Starting Twitter...";
					break;
					
				}
				case GOOGLE:
				{
					
					mainTitle = "Starting Google...";
					break;
					
				}
				case YAHOO:
				case AOL:
				case HOTMAIL:
				case LINKEDIN:
				{
					
					mainTitle = "Starting OpenID...";
					break;
					
				}
					
				default:
				{
					
					mainTitle = "Starting...";
					break;
					
				}
					
			}
			
			return mainTitle;
		}
		
	}
	
}